package com.weizai.carshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weizai.carshop.mapper.AddressMapper;
import com.weizai.carshop.model.dto.InsertAddressDto;
import com.weizai.carshop.model.entiity.AddressEntity;
import com.weizai.carshop.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressEntity> implements AddressService {

    /*
     * 新增或编辑地址
     * */
    @Override
    @Transactional
    public void Insert(InsertAddressDto dto) {
        // 拷贝数据
        AddressEntity address = BeanUtil.copyProperties(dto, AddressEntity.class);

        // 判断是否有默认地址
        if(address.getIsDefault()) {
            // 批量将其他默认地址取消
            UpdateWrapper<AddressEntity> isDefault = new UpdateWrapper<AddressEntity>()
                    .setSql("is_default = 0")
                    .eq("is_default", 1);
            update(isDefault);
        }

        if(address.getId() == null) {
            address.setCreateTime(LocalDateTime.now());
            address.setUpdateTime(LocalDateTime.now());
        }else {
            address.setUpdateTime(LocalDateTime.now());
        }

        this.saveOrUpdate(address);
    }
}
